package com.foreveross.proxyip.core.http.ipdoload;

import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.foreveross.proxyip.entity.ExtractLogEntity;
import com.foreveross.proxyip.entity.IpWebsiteEntity;
import com.foreveross.proxyip.entity.ProxyIpBean;
import com.foreveross.proxyip.exception.ProxyIpServiceException;
import com.foreveross.proxyip.infra.IProxyIpOriginal;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;

public abstract class AbsProxyIpOriginal implements IProxyIpOriginal {
	//数据库操作类，因为该类为抽象类，不能用注解注入，所以从继承子类获取。
		protected IBaseRepository baseRepository;
		/**
		 * 从网上下载IP数同时插入数据库
		 * @param proxyIpMap 池中已经存在的ip，下载ip时排出掉
		 * @param website 下载网站模板对象
		 * @param num 下载数量
		 * @return
		 * @throws Exception
		 */
		public synchronized void  extract(Map<String,ProxyIpBean> proxyIpMap,IpWebsiteEntity website,Integer num) throws Exception {
//			List<ProxyIpBean> list = null;
			ExtractLogEntity extractLog = new ExtractLogEntity();
			extractLog.setBeginTime(new Date());
			String s = null;
			Long preTime = System.currentTimeMillis();
			Integer oldSize = proxyIpMap.size();
			
			try{
				
				this.loadProxyIpMap(proxyIpMap,website,extractLog, num);
				extractLog.setState(1);
			}catch(Exception e){
				extractLog.setState(0);
				s=ProxyIpServiceException.getStackTrace(e);
				throw e;
			}finally{//下载出错信息写入数据库
				if(StringUtils.isNotBlank(s)){
					if(s.length()>1000){
						extractLog.setExtractOtherMessage(s.substring(0,1000));
					}else{
					extractLog.setExtractOtherMessage(s);
					}
				}
				String extractName = website == null ?"数据库":website.getName();
				if(proxyIpMap.size()==0){
					extractLog.setState(0);
					extractLog.setExtractOtherMessage("下载器"+extractName+"出错，下载IP为空!");
//					extractLog.setState(0);
					extractLog.setActualNum(0);
				}else{
					extractLog.setActualNum(proxyIpMap.size()-oldSize);
//					extractLog.setExtractNum(proxyIpMap.size()-oldSize);
				}
				Long endTime = System.currentTimeMillis();
				Long expendTime = endTime-preTime;
				extractLog.setExpendTime(expendTime);
				extractLog.setEndTime(new Date());
				extractLog.setCreateTime(new Date());
				
				extractLog.setExtractMode(extractName);
				if(extractLog.getExtractNum()==null){
					extractLog.setExtractNum(0);
				}
				baseRepository.save(extractLog);
			}
//			return list;
		}

	/**
	 * 加载集合
	 * @param proxyIpMap
	 * @param wegsite
	 * @param num
	 * @throws Exception
	 */
	public abstract void loadProxyIpMap(Map<String,ProxyIpBean> proxyIpMap,IpWebsiteEntity wegsite,ExtractLogEntity extractLog,Integer num) throws Exception ;
	
	public void removeExistIp(Map<String ,ProxyIpBean> extractMap,Map<String ,ProxyIpBean> ipStoreMap){
		Set <String>set = extractMap.keySet();
		for(String ip :set){
			if(ipStoreMap.containsKey(ip)){
				extractMap.remove(ip);
			}
		}
	}
}
